<template>
  <section class="main">
      <input class="toggle-all" type="checkbox" v-model="isCheckedAll" />
      <ul class="todo-list">
          <li v-for="item,index of comPut" :key="item.id" :class="{'completed': item.checked,'editing': index === editTodoIndex}" >
              <div class="view">
                  <input class="toggle" type="checkbox" v-model="item.checked" />
                  <label @dblclick="editTodo(index)">{{item.title}}</label>
                  <button @click="remove(index);" class="destroy"></button>
              </div>
              <input class="edit"
                ref="editCreent"
                @keyup.esc="editCancel(item)"
                v-model="item.title"
                @blur="save(item,index)"
                @keyup.13="save(item,index)" />
          </li>
      </ul>
  </section>
</template>
<script>
  import filterActive from '@/tools/methods.js'
  export default {
    name:'Content',
    data(){
      return {
        editTodoIndex: -1,
        beforeTitle:'',
      }
    },
    computed:{
      comNoPut(){
        return this.$store.state.list;
      },
      comPut(){
        return filterActive[this.$store.state.hash](this.$store.state.list);
      },
      isCheckedAll: {
          get(){
              return this.comPut.every(item => item.checked)
          },
          set(newValue){
              this.$store.commit('setItem',newValue)
          }
      }
    },
    methods:{
      remove(id){
        this.$store.commit('remove',id)
      },
      editTodo(id){
        this.editTodoIndex = id;
        this.$nextTick( () => {
            this.$refs.editCreent[id].focus();
        })
        this.beforeTitle = this.comPut[id].title;
      },
      save(item,id){
          if(!item.title.trim()){
              let itemIndex = this.comPut.findIndex(option => option === item)
              this.$store.commit('remove',itemIndex)
          }
          this.editTodoIndex = -1;
          if(this.beforeTitle == item.title) return;
          this.beforeTitle = '';
          this.$store.commit('save',{
            id:id,
            item:item
          });
      },
      editCancel (item) {
          this.editTodoIndex = -1;
          item.title = this.beforeTitle;
      }
    }
  }
</script>
